<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .container {
            width: 600px;
            height: 600px;
            background-color: #eee;
            border: 2px solid #999;
            position: relative;
            margin: 0 auto;
        }

        #food div {
            position: absolute;
            width: 20px;
            height: 20px;
        }

        ul {
            margin: 0;
            padding: 0;
            list-style-type: none;
        }

        ul li {
            position: absolute;
            width: 20px;
            height: 20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div id="food"></div>
        <div id="sanke">
            <ul>
            </ul>
        </div>
    </div>
    <script>
        const container = document.querySelector(".container");
        const food = document.querySelector("#food");
        const sankebox = document.querySelector("#sanke ul");
        // 随机位置函数
        function place() {
            const num = Math.floor(Math.random() * 20)
            return num * 20
        };
        // 随机颜色函数
        function color() {
            const data = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
            let str = ''
            for (let i = 0; i < 6; i++) {
                str += data[Math.floor(Math.random() * 16)]
            }
            return '#' + str
        };
        //贪吃蛇模块
        let sanke = [
            {
                color: 'red',
                top: 1,
                left: 2,
            },
            {
                color: 'yellow',
                top: 1,
                left: 1,
            },
            {
                color: 'green',
                top: 1,
                left: 0,
            },
        ]
        let len = 3;
        renderSankeList()
        function renderSankeList() {
            let str = '';
            sanke.forEach(function (item, index) {
                str += `<li id="${index}" style="top: ${item.top * 20}px; left: ${item.left * 20}px; background: ${item.color}"></li>`
            })
            sankebox.innerHTML = str
        }
        let direct = 'right'
        let num1 = place();
        let num2 = place();
        function Move() {
            setInterval(function () {
                for (let i = sanke.length - 1; i > 0; i--) {
                    sanke[i].top = sanke[i - 1].top;
                    sanke[i].left = sanke[i - 1].left;
                }
                switch (direct) {
                    case 'left':
                        sanke[0].left--;
                        break;
                    case 'down':
                        sanke[0].top++;
                        break;
                    case 'up':
                        sanke[0].top--;
                        break;
                    case 'right':
                        sanke[0].left++;
                        break;
                }
                // 吃食物功能
                // 撞自己功能
                for (let j = 1; j < len - 1; j++) {
                    if (sanke[j].top * 20 == num1 && sanke[j].left * 20 == num2) {
                        // 定义吃到食物自身增长的长度
                        for (let h = 0; h < 1; h++) {
                            sanke.push({
                                color: color(),
                                top: sanke[1].top,
                                left: sanke[1].left,
                            })
                        }
                        num1 = place();
                        num2 = place();
                        len += 1;
                    }
                    if (sanke[0].top == sanke[j].top && sanke[0].left == sanke[j].left) {
                        alert('撞到自己了,游戏结束，点击确定重新开始');
                        direct = 'right'
                        sanke = [
                            {
                                color: 'red',
                                top: 1,
                                left: 2,
                            },
                            {
                                color: 'yellow',
                                top: 1,
                                left: 1,
                            },
                            {
                                color: 'green',
                                top: 1,
                                left: 0,
                            },
                        ]
                        len = 3;
                    }
                }
                // 撞墙功能
                if (sanke[0].top === 30 || sanke[0].top === -1 || sanke[0].left === 30 || sanke[0].left === -1) {
                    alert('撞墙了，游戏结束，点击确定重新开始');
                    direct = 'right'
                    sanke = [
                        {
                            color: 'red',
                            top: 1,
                            left: 2,
                        },
                        {
                            color: 'yellow',
                            top: 1,
                            left: 1,
                        },
                        {
                            color: 'green',
                            top: 1,
                            left: 0,
                        },
                    ];
                    num1 = place();
                    num2 = place();
                    len = 3;
                }
                foodBlock();
                renderSankeList();
            }, 100)

        }
        document.addEventListener('keyup', function (e) {
            if (direct != 'down' && e.code == 'KeyW' || e.code == 'ArrowUp' && direct != 'down') {
                direct = 'up'
            } else if (direct != 'left' && e.code == 'KeyD' || e.code == 'ArrowRight' && direct != 'left') {
                direct = 'right'
            } else if (direct != 'right' && e.code == 'KeyA' || e.code == 'ArrowLeft' && direct != 'right') {
                direct = 'left'
            } else if (direct != 'up' && e.code == 'KeyS' || e.code == 'ArrowDown' && direct != 'up') {
                direct = 'down'
            }
        })

        // 食物模块
        function foodBlock() {
            const foods = document.createElement('div');
            food.innerHTML = '';
            food.appendChild(foods);
            foods.style = `background: ${color()}; top: ${num1}px; left: ${num2}px`
        };
        Move()

    </script>
</body>

</html>